package com.tecent.chat.actvity;

import android.content.Intent;
import android.content.IntentFilter;
import android.media.Image;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;

import androidx.appcompat.app.AppCompatActivity;

import com.tecent.chat.R;
import com.tecent.chat.broadcast.NetworkReceiver;
import com.tecent.chat.utils.HttpUtils;

import java.io.IOException;


class SendUrlTask extends AsyncTask<Void, Void, String> {

    public String url;

    public WebView webView;

    public SendUrlTask(String url, WebView webView) {
        this.url = url;
        this.webView = webView;
    }

    @Override
    protected String doInBackground(Void... voids) {
        // 进行网路请求
        return HttpUtils.sendUrl(url);
    }

    @Override
    protected void onPostExecute(String s) {
        Log.v("main", s);
        super.onPostExecute(s);
        webView.loadData(s, "text/html;charset=utf-8", null);
    }
}

public class PageActivity extends AppCompatActivity {

    private IntentFilter intentFilter;
    private NetworkReceiver networkReceiver;
    private SendUrlTask sendUrlTask;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_page);

        WebView webView=findViewById(R.id.web1);//绑定ID
        webView.setWebViewClient(new WebViewClient());//添加WebViewClient实例
        // webView.loadUrl("file:///android_asset/demo.html");//添加浏览器地址

        ImageView img= findViewById(R.id.img11);

        WebSettings webSettings = webView.getSettings();

        // 启用js
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setDatabaseEnabled(true);

        sendUrlTask = new SendUrlTask("http://www.baidu.com", webView);
        sendUrlTask.execute();

        String type = "android.net.conn.CONNECTIVITY_CHANGE";
        intentFilter = new IntentFilter();
        intentFilter.addAction(type);

        networkReceiver = new NetworkReceiver();
        registerReceiver(networkReceiver, intentFilter);

        // 点击按钮，发送广播
        Button btn = findViewById(R.id.btn_b);
        btn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Intent intent = new Intent("com.tecent.chat.MY_BROADCAST");
                sendBroadcast(intent);
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(sendUrlTask != null){
            sendUrlTask.cancel(true);
        }
        // 销毁活动，要结束广播接收
        unregisterReceiver(networkReceiver);
    }
}
